package com.example.ymm.util;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.example.ymm.exception.YmException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.sql.Timestamp;
import java.util.Date;

//@Component
@Slf4j
public class OssUtil {

    static String bucketName = "liuqingfeng-read-buket";
    static String domain = "oss-cn-shenzhen.aliyuncs.com";
    static String accessKeyId = "LTAI5tAFq95yqvgVMrjAD7Jb";
    static String accessKeySecret = "xTqmQggkdsjx7CveOdU5bOtBq0b7Xz";

    public static void main(String[] args) throws Exception {

        String url="https://resource/eb24b06da9ed88f4da5ed9fc9972c2a.audio";
        Timestamp createTime=new Timestamp(new Date().getTime());
        String s = testUploadAudioFn(url, createTime);
        System.out.println(s);
    }

    public static String uploadOggFn(String oggUrl, Timestamp createTime) {
        String result = null;
        try {
            String fileName = oggUrl.split("https://static.dingtalk.com/media/")[1];
            fileName = fileName.replaceAll("\\.ogg", "\\.mp3");
            String path = "";
            path = "/usr/local/file/video/temp/";
//            path="D:/file/";
            String savePath = path + fileName;
            File file = new File(savePath);
            URL url = new URL(oggUrl);
            ConvertingAnyAudioToMp3.amrInputStreamToMp3(url, file);
            result = uploadByInputStream(file, createTime);
            file.delete();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }


    public static String testUploadAudioFn(String oggUrl, Timestamp createTime) {
        String result = null;
        try {
            String fileName = oggUrl.split("https://resource/")[1];
            fileName = fileName.replaceAll("\\.audio", "\\.mp3");
            String path = "";
//            path = "/usr/local/file/video/temp/";
            path="D:/file/";
            String savePath = path + fileName;
            File file = new File(savePath);
            URL url = new URL(oggUrl);
            ConvertingAnyAudioToMp3.amrInputStreamToMp3(url, file);
            result = uploadByInputStream(file, createTime);
            file.delete();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * mp3文件上传
     *
     * @param file
     * @param createTime
     * @return
     */
    public static String uploadByInputStream(File file, Timestamp createTime) {

        String fileName = file.getName();
        String dates = DateKit.dateFormat(new Date(createTime.getTime()), "yyyy-MM-dd");

        String result = null;
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。

        String endpoint = "https://" + domain;
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
//        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);

        // 填写Bucket名称，例如examplebucket。
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "video/" + dates + "/" + fileName;

        result = "https://" + bucketName + "." + domain + "/" + objectName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            FileInputStream inputStream = new FileInputStream(file);
//            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(inputStream.getBytes()));
            ossClient.putObject(bucketName, objectName, inputStream);

        } catch (Exception oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getMessage());
            throw new YmException("Error Message:" + oe.getMessage());

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return result;
    }

    /**
     * 查询文件是否存在
     * @param url
     * @return
     */
    public static boolean existFile(String url) {
        boolean result = false;
        try {
            // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
            String endpoint = "https://" + domain;
            // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
            // 填写Bucket名称，例如examplebucket。
            // 填写不包含Bucket名称在内的Object完整路径，例如exampleobject.txt。

            String replaceStr = "https://" + bucketName + "." + domain + "/";
            String objectName = url.replaceAll(replaceStr, "");

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);


            // 判断文件是否存在。如果返回值为true，则文件存在，否则存储空间或者文件不存在。
            // 设置是否进行重定向或者镜像回源。默认值为true，表示忽略302重定向和镜像回源；如果设置isINoss为false，则进行302重定向或者镜像回源。
            //boolean isINoss = true;
            result = ossClient.doesObjectExist(bucketName, objectName);

        } catch (OSSException oe) {
            System.out.println("Error Message:" + oe.getErrorMessage());
            throw new YmException(oe.getErrorMessage());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {

        }
        return result;
    }


    /**
     * 普通文件上传
     *
     * @param file
     * @param
     * @return
     */
    public static String uploadFileByMultipartFile(MultipartFile file) {

        String fileName = file.getOriginalFilename();
        String dates = DateKit.dateFormat(new Date(), "yyyy-MM-dd");

        String result = null;
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。

        String endpoint = "https://" + domain;
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
//        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);

        // 填写Bucket名称，例如examplebucket。
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "excel/" + dates + "/" + fileName;

        result = "https://" + bucketName + "." + domain + "/" + objectName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            InputStream inputStream = file.getInputStream();
//            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(inputStream.getBytes()));
            ossClient.putObject(bucketName, objectName, inputStream);

        } catch (Exception oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getMessage());
            throw new YmException("Error Message:" + oe.getMessage());

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return result;
    }

    /**
     * 普通图片上传 到oss
     *
     * @param file
     * @param
     * @return
     */
    public static String uploadImgByMultipartFile(MultipartFile file) {

        String fileName = file.getOriginalFilename();
        String dates = DateKit.dateFormat(new Date(), "yyyy-MM-dd");

        String result = null;
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。

        String endpoint = "https://" + domain;
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
//        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);

        // 填写Bucket名称，例如examplebucket。
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "images/" + dates + "/" + fileName;

        result = "https://" + bucketName + "." + domain + "/" + objectName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            InputStream inputStream = file.getInputStream();
//            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(inputStream.getBytes()));
            ossClient.putObject(bucketName, objectName, inputStream);

        } catch (Exception oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getMessage());
            throw new YmException("Error Message:" + oe.getMessage());

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return result;
    }

}
